Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!
In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.
There are three main parts to this project:
Part 1 : Investigating OpenCV, pre-processing, and face detection
Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints
Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!
*Here's what you need to know to complete the project:
In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.
a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.
a. Each section where you will answer a question is preceded by a 'Question X' header.
b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.
Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.
Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.
In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!
The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.
Part 1 : Investigating OpenCV, pre-processing, and face detection
Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints
Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!
Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.
At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.
We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.
In the next python cell, we load in the required libraries for this section of the project.
# Import required libraries for this section
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import math
import cv2 # OpenCV library for computer vision
from PIL import Image
import time
Next, we load in and display a test image for performing face detection.
Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.
This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.
Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!
To learn more about the parameters of the detector see this post.
# Convert the RGB image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.
To test your eye detector, we'll first read in a new test image with just a single face.
# Load in color image for face detection
image = cv2.imread('images/james.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.
So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.
# Convert the RGB image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.25, minNeighbors=6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.
To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.
A few notes before you get started:
First, make sure to give your loaded eye detector the variable name
eye_cascade
and give the list of eye regions you detect the variable name
eyes
Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.
Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.
# Make a copy of the original image to plot rectangle detections
def detect(image, face_cascade, eye_cascade):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
image_with_detections = np.copy(image)
assert face_cascade is not None, "No face cascade provided"
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.25, minNeighbors=6)
# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)
# Do not change the code above this comment!
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
if eye_cascade is not None:
for (x,y,w,h) in faces:
gray_face = gray[y:y+h, x:x+w]
color_face = image_with_detections[y:y+h, x:x+w, :]
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
# print ("Doing eye detection")
eyes = eye_cascade.detectMultiScale(gray_face, scaleFactor=1.15, minNeighbors=3)
# print ("Count of eyes: ", len(eyes))
for (p,q,r,s) in eyes:
cv2.rectangle(color_face, (p,q), (p+r,q+s),(0,255,0), 3)
return image_with_detections, faces
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
image_with_detections, _ = detect(image, face_cascade, eye_cascade)
# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.
The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.
Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.
Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!
### Add face and eye detection to this laptop camera function
# Make sure to draw out all faces/eyes found in each frame on the shown video feed
import cv2
import time
import random
# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Keep the video stream open
while rval:
# Plot the image from camera with all the face and eye detections marked
frame, _ = detect(frame, face_cascade, eye_cascade)
cv2.imshow("face detection activated", frame)
# Exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # Exit by pressing any key
# Destroy windows
cv2.destroyAllWindows()
# Make sure window closes on OSx
for i in range (1,5):
cv2.waitKey(1)
return
# Read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
# Call the laptop camera face/eye detector function above
# laptop_camera_go()
Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!
When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.
In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.
In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')
# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Make an array copy of this image
image_with_noise = np.asarray(image)
# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level
# Add this noise to the array image copy
image_with_noise = image_with_noise + noise
# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])
# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.
In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.
# Convert the RGB image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
With this added noise we now miss one of the faces!
Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.
You can find its official documentation here and a useful example here.
Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!
denoised_image = cv2.fastNlMeansDenoisingColored(src=image_with_noise, dst=None, h=13, hColor=10, templateWindowSize=7, searchWindowSize=21)# your final de-noised image (should be RGB)
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('De-Noised Image')
ax1.imshow(denoised_image)
## TODO: Run the face detector on the de-noised image to improve your detections and display the result
# Convert the RGB image to grayscale
gray_denoised = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_denoised, 4, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
denoised_image_with_detections = np.copy(denoised_image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(denoised_image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(denoised_image_with_detections)
Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!
Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.
Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.
Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.
In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.
# Load in the image
image = cv2.imread('images/fawzia.jpg')
# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)
# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)
# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).
In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.
Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.
### TODO: Blur the test imageusing OpenCV's filter2d functionality,
# Use an averaging kernel, and a kernel width equal to 4
averaging_kernel = np.ones((4,4),np.float32)/16
blurred_image = cv2.filter2D(gray,-1, averaging_kernel)
## TODO: Then perform Canny edge detection and display the output
wide = cv2.dilate(cv2.Canny(blurred_image, 20, 190), None)
tight = cv2.dilate(cv2.Canny(blurred_image, 70, 120), None)
# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Wide Detections')
ax1.imshow(wide, cmap='gray')
ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Narrow Detections')
ax2.imshow(tight, cmap='gray')
If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.
# Load in the image
image = cv2.imread('images/gus.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.
def censor(image):
## TODO: Implement face detection
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
faces_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
faces = faces_cascade.detectMultiScale(gray, 1.10, 10)
# print ("Faces detected: ", len(faces))
## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
censored_image = np.copy(image)
# print(censored_image.shape)
averaging_kernel = np.ones((61,61),np.float32)/(61*61)
for (x,y,w,h) in faces:
# print(x,y,w,h)
face = censored_image[y:y+h, x:x+w, :]
# print (face.shape)
# face = cv2.GaussianBlur(face,(49, 49), 30) # This does a good blurring. Saving for future reference!
face = cv2.filter2D(face, -1, averaging_kernel) #
censored_image[y:y+h, x:x+w, :] = face
for (x,y,w,h) in faces:
cv2.rectangle(censored_image, (x,y), (x+w,y+h), (255,0,0), 5)
return censored_image
censored_image = censor(image)
# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Concealed Image')
ax1.imshow(censored_image, cmap='gray')
In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.
The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.
Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.
Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Keep video stream open
while rval:
# Plot image from camera with detections marked
frame = censor(frame)
cv2.imshow("face detection activated", frame)
# Exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # Exit by pressing any key
# Destroy windows
cv2.destroyAllWindows()
for i in range (1,5):
cv2.waitKey(1)
return
# Read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
# Run laptop identity hider
# laptop_camera_go()
OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.
You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.
Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.
In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.
To load in this data, run the Python cell below - notice we will load in both the training and testing sets.
The load_data function is in the included utils.py file.
from utils import *
# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
y_train.shape, y_train.min(), y_train.max()))
# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.
Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.
Execute the code cell below to visualize a subset of the training data.
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_train[i], y_train[i], ax)
For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.
Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.
Specify your architecture below. Once done, you'll need to compile and train the model to detect facial keypoints.
Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.
Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5 (or as appropriate for book-keeping).
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam
from keras import metrics
from keras.callbacks import EarlyStopping
from keras import metrics
import os
def train_model(model, model_file, reload=False, train=True, dry=False, epochs=60, batch_size=32, patience=25):
if reload and os.path.isfile(model_file):
print ("Continuing training from previous saved model weights...")
model.load_weights(model_file)
else:
print ("Starting training from scratch...")
## TODO: Train the model
if train:
print ("Training the model...")
callbacks = []
callbacks.append(EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=patience, verbose=1, mode='min'))
print (X_train.shape, y_train.shape, np.min(X_train), np.max(X_train), np.min(y_train), np.max(y_train))
print (np.max(np.isnan(X_train)))
print (np.max(np.isnan(y_train)))
hist = model.fit( X_train, y_train, validation_split=0.2, batch_size=batch_size, nb_epoch=epochs, callbacks=callbacks, verbose=1 )
else:
print ("Training disabled.")
## TODO: Save the model as model.h5
if not dry and train:
model.save(model_file)
else:
print ("Saving disabled.")
if train:
## TODO: Visualize the training and validation loss of your neural network
plt.plot(hist.history['acc'])
plt.plot(hist.history['val_acc'])
plt.title('Training and validation accuracies')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# summarize history for training loss and validation loss
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Training and validation losses')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
else:
print ("Nothing to show because no training was done")
In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.
Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.
Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-3cn-1fc-nodrop-mse-rmsprop.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
# model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
# model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
# model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='rmsprop',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=60, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-3cn-1fc-drop-mse-rmsprop.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(Dropout(0.5))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
# model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
# model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
# model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='rmsprop',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=200, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-3cn-1fc-drop-mse-adam.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(Dropout(0.5))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
# model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
# model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
# model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=200, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense, BatchNormalization
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-3cn-1fc-drop-batchnorm-mse-adam.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
model.add(Dropout(0.5))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
# model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
# model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
# model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=200, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-4cn-2fc-nodrop-mse-rmsprop.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='rmsprop',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=60, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-4cn-2fc-drop-mse-rmsprop.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(Dropout(0.5))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='rmsprop',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=60, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-4cn-2fc-nodrop-mse-adam.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=200, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-4cn-2fc-drop-mse-adam.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1
model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(Dropout(0.5))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100
model.add(Dense(100))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=200, batch_size=32, patience=25)
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout, BatchNormalization
from keras.layers import Flatten, Dense
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
model_file = "my_model.h5-4cn-2fc-batchnorm-drop-mse-adam.hd5"
model = Sequential()
# Input Layer: 96 x 96 input neurons
# Convolution Layer 1: 96x96 [filter/same: 3x3] -> 96 x 96 x 10-> maxpooling 2:1 -> BatchNorm
model.add(Convolution2D(filters=6, kernel_size=3, strides=(1,1), padding='same', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
# Convolution Layer 2: 48 x 48 [filter/same: 3x3] -> 48 x 48 x 20 -> maxpooling 2:1 -> BatchNorm
model.add(Convolution2D(filters=12, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
# Convolution Layer 3: 24 x 24 [filter/same: 3x3] -> 24 x 24 x 30 -> maxpoolling 2:1 -> BatchNorm
model.add(Convolution2D(filters=24, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
# Convolution Layer 4: 12 x 12 [filter/same: 3x3] -> 12 x 12 x 60 -> maxpooling 2:1 -> BatchNorm -> Dropout
model.add(Convolution2D(filters=48, kernel_size=3, strides=(1,1), padding='same'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
model.add(Dropout(0.5))
# Flatten
model.add(Flatten())
# # FCN: 12 x 12 x 60 -> 100 -> BatchNorm
model.add(Dense(100, activation='relu'))
model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001))
# FCN: 144 -> 30
model.add(Dense(30))
# Summarize the model
model.summary()
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['acc', 'mae', 'mse'] )
train_model(model, model_file, reload=False, train=True, dry=False, epochs=200, batch_size=32, patience=25)
Here are the results of training using 2 optimizers (Adam and RMSProp), and in each case, using no dropout, then using dropout, and then adding additional batch normalization.
| Architecture | Epochs | Train Loss | Val Loss | Train Acc | Val Acc |
|---|---|---|---|---|---|
| 3CN/1FC/RMSProp/NoDrop | 38 | 0.0006 | 0.0018 | 88 | 78 |
| 3CN/1FC/RMSProp/Drop | 52 | 0.0013 | 0.0015 | 81 | 79 |
| 3CN/1FC/Adam/Drop | 96 | 0.0009 | 0.0013 | 81 | 81 |
| 3CN/1FC/Adam/Drop/Batch | 70 | 0.0063 | 0.0034 | 68 | 72 |
| 4CN/2FC/RMSProp/NoDrop | 46 | 0.0004 | 0.0020 | 88 | 75 |
| 4CN/2FC/RMSProp/Drop | 50 | 0.0009 | 0.0013 | 80 | 78 |
| 4CN/2FC/Adam/NoDrop | 45 | 0.0004 | 0.0016 | 86 | 79 |
| 4CN/2FC/Adam/Drop | 85 | 0.0008 | 0.0012 | 81 | 78 |
| 4CN/2FC/Adam/Drop/Batch | 133 | 0.0017 | 0.0016 | 77 | 78 |
Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.
Answer: My goal is generally to create the smallest network that overfits to the training set. And then find ways to regularize it to improve the validation performance. In all cases below, I had setup early stopping with a patience of 25 epochs and an expected reduction in validation loss of at least 0.0001 units for training to continue.
I found that with 3 convolutional layers and 1 fully-connected layer, the network achieved pretty satisfactory results. Without dropout, the network overfitted to the training set and underfitted to the validation set by a factor of ~10% in accuracy. The losses too were accordingly wide apart. This was also obvious through manual testing. For example, the network would not adjust its keypoints when the subject's mouth was not in a closed position, nor when the eyes and eyebrows would wince. It had learned a set of patterns of points, and was not adapting too well to variations in faces. However, training was pretty fast, even on my Macbook, since there were only ~100K parameters to train.
I then added regularization through a dropout layer, which drastically improved the performance on the validation set, however, at the expense of increasing the bias (as can be seen in the table above). The best validation performance achieved with 3 convolutional layers, 1 fully connected layer, and dropout was a loss of 0.0013 and accuracy of 81%.
Below is an illustration of the difference that regularization made, on the network above:
![]() |
![]() |
|---|
It was for curiosity that I attempted increasing the depth of the network by using 4 convolution layers and 2 fully-connected layers to see if it would improve the performance overall. Again, I tested without any regularization (no dropout). Strangely, the network didn't seem to do any better on the training data than using fewer layers, though that might also be because of early stopping kicking in too early. However, I am not convinced this was the case. The network trained for more epochs, which makes sense since there were now ~189K parameters to train, but the overfitted performance was the same as the prior architecture.
I then attempted regularization by adding a dropout layer. This achieved a marked improvement in validation loss, reaching as low as 0.0012 units for validation data. However, validation accuracy remained around 78%, which was in the same ballpark as the performance in the prior architecture. This was the lowest validation loss I had achieved so far, and I decided to use that architecture (and trained model) for the rest of this project. That model is saved in the file named: ''.
Here is the difference that regularization made on the deeper network:
![]() |
![]() |
|---|
The reason I used only 1 dropout (and no more) in both network architectures above, is that even with that on dropout, the accuracy that the network achieved for both training and validation sets converged. There didn't seem to be a reason to add more regularization in this case, because the only difference that would have made would have been to increase both the training time and the bias.
Another behavior I saw was with the performance of the both network architectures above, after adding BatchNormalization (in addition to Dropout). Not only did the networks continue training beyond what they did without BN, but they also performed at best the same on both training and validation sets, as compared to the performance of the respective architectures without batch normalization. For these two reasons, I stuck to just 1 dropout layer, and no batch normalization, for the 'winning' network.
Below is an illustration of the difference that batch normalization produced, on the shallower network:
![]() |
![]() |
|---|
And below is the difference it made for the deeper network:
![]() |
![]() |
|---|
The only explanation I can come up with, for the two strange behaviors above -- i.e, (a) that a deeper network didn't seem to have higher variance than the shallower one, and (b) that batch normalization required more epochs of training, and still didn't produce better results -- is that the eary stopping feature that I relied on might have aborted training too soon in both cases. Perhaps a patience of 25 is too short, and a reduction of 0.0001 units of validation loss was too high of an expectation at each epoch. Perhaps if the settings were more lenient, the more complex network architecture with batch normalization would have come out as the winner.
In any case, I had achieved a substantially good validation loss (0.0012) and validation accuracy (78%), for the purposes of this project, and decided not to go any further down that rabbit hole. 4 convolution layers + 2 fully-connected layers, with one dropout (of 50% drop probability), was the winning architecture. The only remaining item was the selection of the optimizer, which I have discussed next.
Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?
Answer: I tried 2 optimizers - RMSProp and Adam. Adam is considered one of the better performing optimizers, and it lived up to that reputation in my tests.
I based the decision (about which one worked best) on the final validation loss and accuracy that was achieved using each of the 2 optimizers, keeping all else equal. In other words, in all cases, i.e, with both a shallower or deeper network, and both with or without a dropout, Adam achieved better numbers than RMSProp.
Below is the performance of the shallower network with regularization, using RMSProp and Adam:
![]() |
![]() |
|---|
And below is the same for the deeper network, again using RMSProp and Adam:
![]() |
![]() |
|---|
Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).
Answer: I have already discussed at length the process that I followed when adding regularization to both network architectures above. There indeed was overfitting observed -- nearly a 8-10% difference in accuracy between training and validation sets, when no regularization was used.
Below are the performances of the two network architectures, without regularization:
![]() |
![]() |
|---|
Below are the performances of the same two network architectures, after adding regularization (1 dropout of 50% probability):
![]() |
![]() |
|---|
There are potentially other things I could have explored to improve the overall performance of the network:
Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_test[i], y_test[i], ax)
With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now
In this Subsection you will do just this!
Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps
Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.
When complete you should be able to produce example images like the one below

# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plot our image
def show(image):
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image)
show(image)
from sklearn.preprocessing import normalize
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
image_with_faces, face_regions = detect(image, face_cascade, None)
print ("Number of faces: ", len(face_regions))
#
# Method to map a function to a list of faces on a given image
#
def process_faces(image, faces, callback):
image = np.copy(image)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
if faces is not None:
for (x,y,w,h) in faces:
face_color = image[y:y+h, x:x+w, :]
face_gray = gray[y:y+h, x:x+w]
processed_color = callback(face_color, face_gray)
image[y:y+h, x:x+w, :] = processed_color
return image
def find_keypoints(face_gray):
# Resize image to 96x96
resized_gray = cv2.resize(face_gray, (96,96))
# Normalize to range [0,1]
face_gray_norm = normalize(resized_gray, axis=0, norm='l1')
# Query model for keypoints
global model
X = np.reshape(face_gray_norm, (1,96,96,1))
# show(X[0,:,:,0]) # If this gets drawn, it means it was reshaped well
points = model.predict(X)
points = points * 48 + 48 # undo the normalization
# Obtain the X and Y coordinates of each keypoint:
xs = points[0,0::2]
ys = points[0,1::2]
# Adjust keypoints for original sized image:
keypoints = [(int(face_gray.shape[0]/96 * x), int(face_gray.shape[1]/96 * y)) for (x,y) in zip(xs,ys)]
return keypoints
def draw_points(face_color, points):
marked = np.copy(face_color)
for (x,y) in points:
marked = cv2.circle(marked, (x,y), 4, (0,255,0),thickness=-1)
return marked
def mark_facial_keypoints(face_color, face_gray):
keypoints = find_keypoints(face_gray)
marked = draw_points(face_color, keypoints)
return marked
processed_image = process_faces(image, face_regions, mark_facial_keypoints)
## TODO : Paint the predicted keypoints on the test image
show(processed_image)
Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!
import cv2
import time
from keras.models import load_model
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# keep video stream open
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
while rval:
# plot image from camera with detections marked
_, face_regions = detect(frame, face_cascade, None)
# print ("Number of faces: ", len(face_regions))
marked = process_faces(frame, face_regions, mark_facial_keypoints)
cv2.imshow("face detection activated", marked)
# exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # exit by pressing any key
# destroy windows
cv2.destroyAllWindows()
# hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
for i in range (1,5):
cv2.waitKey(1)
return
# read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
# Run your keypoint face painter
# laptop_camera_go()
Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)
# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');
This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).
Notice that this image actually has 4 channels, not just 3.
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.
This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.
Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)
# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).
One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
image_with_faces, face_regions = detect(image, face_cascade, None)
print ("Number of faces: ", len(face_regions))
#KeypointIDs:
LeftEyeLeftCorner = 3
LeftEyeRightCorner = 2
LeftEyeCenter = 0
LeftEyebrowLeftCorner = 7
LeftEyebrowRightCorner = 6
RightEyeRightCorner = 5
RightEyeLeftCorner = 4
RightEyeCener = 1
RightEyebrowLeftCorner = 8
RightEyebrowRightCorner = 9
NoseCenter = 10
def overlay_sunglasses(face_color, keypoints):
# Sunglass adjustments:
# - Length: distance between LeftEyeLeftCorner[x]' and 'RightEyeRightCorner[x]'
# Since we are not dealing with sunglass orientation right now. So we take
# the length only along the X-axis.
length = int((keypoints[LeftEyebrowLeftCorner][0] - keypoints[RightEyebrowRightCorner][0]) * 1.35)
# - Height: distance between LeftEyebrowRightCorner[y] and NoseCenter[y]
# Same as above reason: No orientation, so height is calculated only along y axis.
height = keypoints[NoseCenter][1] - keypoints[LeftEyebrowRightCorner][1]
assert length > height
# - Position: mid-point of lower edge sits right above the NoseCenter
nose = keypoints[NoseCenter] # expected position of the mid-point of lower edge of 'sunglasses'
# - Orientation: sunglass's euler angles are out of scope for this project.
global sunglasses
resized_sunglasses = cv2.resize(sunglasses, (length,height))
upper_left = [(nose[0] - int(length/2)), nose[1] - height]
lower_right = [(nose[0] + int(length/2)), nose[1]]
#
# Alpha-blend sunglasses onto face
# See: https://www.learnopencv.com/alpha-blending-using-opencv-cpp-python/
#
# Separate out background, foreground and alpha
blended = np.copy(face_color).astype(float)
background = blended[upper_left[1]:upper_left[1]+height, upper_left[0]:upper_left[0]+length, :]
foreground = np.copy(resized_sunglasses[:,:,:3]).astype(float)
assert background.shape == foreground.shape, "Shapes did not match: {} not equal to {}".format(background.shape, foreground.shape)
alpha = resized_sunglasses[:,:,3].astype(float)/255 # Normalize the alpha mask to keep intensity between 0 and 1
alpha = np.dstack((alpha, alpha, alpha))
# Multiply the foreground with the alpha matte
assert alpha.shape[:2] == foreground.shape[:2], "Shapes did not match: {} not equal to {}".format(alpha.shape, foreground.shape)
foreground = cv2.multiply(alpha, foreground)
# Multiply the background with ( 1 - alpha )
background = cv2.multiply(1.0 - alpha, background)
# Add the masked foreground and background.
blended[upper_left[1]:upper_left[1]+height, upper_left[0]:upper_left[0]+length, :] = cv2.add(foreground, background)
return blended
# marked = np.copy(face_color)
# for (x,y) in keypoints:
# marked = cv2.circle(marked, (x,y), 4, (0,255,0),thickness=-1)
# return marked
def draw_facial_sunglasses(face_color, face_gray):
keypoints = find_keypoints(face_gray)
marked = overlay_sunglasses(face_color, keypoints)
return marked
processed_image = process_faces(image, face_regions, draw_facial_sunglasses)
## TODO : Paint the predicted keypoints on the test image
show(processed_image)
Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!
import cv2
import time
from keras.models import load_model
import numpy as np
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Keep video stream open
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
while rval:
# Plot image from camera with detections marked
image_with_faces, face_regions = detect(frame, face_cascade, None)
frame = process_faces(frame, face_regions, draw_facial_sunglasses)
cv2.imshow("face detection activated", frame)
# Exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # exit by pressing any key
# Destroy windows
cv2.destroyAllWindows()
for i in range (1,5):
cv2.waitKey(1)
return
# Read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
# Load facial landmark detector model
model = load_model('my_model.h5-4cn-2fc-drop-mse-adam.hd5')
# Run sunglasses painter
# laptop_camera_go()